package chapter8;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 等待通知
 *
 * @author eric
 */
public class GuardedQueue {
    private final Queue<Integer> sourceList;

    public GuardedQueue() {
        this.sourceList = new LinkedBlockingQueue<>();
    }

    public synchronized Integer get() {
        while (this.sourceList.isEmpty()) {
            try {
                // 当前线程等待
                wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return sourceList.peek();
    }

    public synchronized void put(Integer e) {
        sourceList.add(e);
        // 通知所有等待的线程
        notifyAll();
    }

}
